package org.example.managere.controller.feibiao;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.example.managere.dto.feibiao.AmKnowledgeEntityDto;
import org.example.managere.service.feibiao.AmKnowledgeEntityService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 知识图谱实体控制器 - 电机向量知识库
 */
@RestController
@RequestMapping("/api/feibiao/knowledge/entity")
@RequiredArgsConstructor
public class AmKnowledgeEntityController {
    
    private final AmKnowledgeEntityService amKnowledgeEntityService;
    
    /**
     * 获取所有知识图谱实体（分页）
     *
     * @param page 页码（从0开始）
     * @param size 每页大小
     * @param sort 排序字段
     * @return 知识图谱实体分页结果
     */
    @GetMapping
    public ResponseEntity<Page<AmKnowledgeEntityDto>> getAllEntities(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false, defaultValue = "entity_id,asc") String sort) {
        Pageable pageable;
        if (sort != null && !sort.isEmpty()) {
            String[] sortParams = sort.split(",");
            String sortField = sortParams[0];
            Sort.Direction direction = (sortParams.length > 1 && sortParams[1].equalsIgnoreCase("desc"))
                    ? Sort.Direction.DESC : Sort.Direction.ASC;
            pageable = PageRequest.of(page, size, Sort.by(direction, sortField));
        } else {
            pageable = PageRequest.of(page, size);
        }
        return ResponseEntity.ok(amKnowledgeEntityService.findAll(pageable));
    }
    
    /**
     * 根据ID获取知识图谱实体
     *
     * @param entityId 实体ID
     * @return 知识图谱实体
     */
    @GetMapping("/{entityId}")
    public ResponseEntity<AmKnowledgeEntityDto> getEntityById(@PathVariable String entityId) {
        return amKnowledgeEntityService.findById(entityId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 创建知识图谱实体
     *
     * @param dto 知识图谱实体DTO
     * @return 创建后的知识图谱实体
     */
    @PostMapping
    public ResponseEntity<AmKnowledgeEntityDto> createEntity(@Valid @RequestBody AmKnowledgeEntityDto dto) {
        return new ResponseEntity<>(amKnowledgeEntityService.save(dto), HttpStatus.CREATED);
    }
    
    /**
     * 更新知识图谱实体
     *
     * @param entityId 实体ID
     * @param dto      知识图谱实体DTO
     * @return 更新后的知识图谱实体
     */
    @PutMapping("/{entityId}")
    public ResponseEntity<AmKnowledgeEntityDto> updateEntity(
            @PathVariable String entityId,
            @Valid @RequestBody AmKnowledgeEntityDto dto) {
        if (!entityId.equals(dto.getEntityId())) {
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok(amKnowledgeEntityService.update(dto));
    }
    
    /**
     * 删除知识图谱实体
     *
     * @param entityId 实体ID
     * @return 无内容响应
     */
    @DeleteMapping("/{entityId}")
    public ResponseEntity<Void> deleteEntity(@PathVariable String entityId) {
        amKnowledgeEntityService.deleteById(entityId);
        return ResponseEntity.noContent().build();
    }
    
    /**
     * 搜索知识图谱实体
     *
     * @param keyword 关键字
     * @param page    页码
     * @param size    每页大小
     * @param sort    排序字段
     * @return 符合条件的知识图谱实体分页结果
     */
    @GetMapping("/search")
    public ResponseEntity<Page<AmKnowledgeEntityDto>> searchEntities(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false, defaultValue = "entity_id,asc") String sort) {
        Pageable pageable;
        if (sort != null && !sort.isEmpty()) {
            String[] sortParams = sort.split(",");
            String sortField = sortParams[0];
            Sort.Direction direction = (sortParams.length > 1 && sortParams[1].equalsIgnoreCase("desc"))
                    ? Sort.Direction.DESC : Sort.Direction.ASC;
            pageable = PageRequest.of(page, size, Sort.by(direction, sortField));
        } else {
            pageable = PageRequest.of(page, size);
        }
        return ResponseEntity.ok(amKnowledgeEntityService.searchByKeyword(keyword, pageable));
    }
    
    /**
     * 根据实体名称查询
     *
     * @param entityName 实体名称
     * @return 知识图谱实体
     */
    @GetMapping("/by-name")
    public ResponseEntity<AmKnowledgeEntityDto> findByEntityName(@RequestParam String entityName) {
        return amKnowledgeEntityService.findByEntityName(entityName)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 根据实体名称模糊查询
     *
     * @param entityName 实体名称
     * @return 符合条件的知识图谱实体列表
     */
    @GetMapping("/name-containing")
    public ResponseEntity<List<AmKnowledgeEntityDto>> findByEntityNameContaining(@RequestParam String entityName) {
        return ResponseEntity.ok(amKnowledgeEntityService.findByEntityNameContaining(entityName));
    }
    
    /**
     * 根据实体类型查询
     *
     * @param entityType 实体类型
     * @return 符合条件的知识图谱实体列表
     */
    @GetMapping("/by-type")
    public ResponseEntity<List<AmKnowledgeEntityDto>> findByEntityType(@RequestParam String entityType) {
        return ResponseEntity.ok(amKnowledgeEntityService.findByEntityType(entityType));
    }
    
    /**
     * 根据实体类型模糊查询
     *
     * @param entityType 实体类型
     * @return 符合条件的知识图谱实体列表
     */
    @GetMapping("/type-containing")
    public ResponseEntity<List<AmKnowledgeEntityDto>> findByEntityTypeContaining(@RequestParam String entityType) {
        return ResponseEntity.ok(amKnowledgeEntityService.findByEntityTypeContaining(entityType));
    }
    
    /**
     * 根据录入时间范围查询
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return 符合条件的知识图谱实体列表
     */
    @GetMapping("/by-entry-time")
    public ResponseEntity<List<AmKnowledgeEntityDto>> findByEntryTimeBetween(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date endDate) {
        return ResponseEntity.ok(amKnowledgeEntityService.findByEntryTimeBetween(startDate, endDate));
    }
    
    /**
     * 统计某个类型的实体数量
     *
     * @param entityType 实体类型
     * @return 实体数量
     */
    @GetMapping("/count-by-type")
    public ResponseEntity<Long> countByEntityType(@RequestParam String entityType) {
        return ResponseEntity.ok(amKnowledgeEntityService.countByEntityType(entityType));
    }
} 